package com.hongxiangly.ip.impl;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hongxiangly.ip.Address;
import com.hongxiangly.ip.IpAddress;
import com.hongxiangly.ip.exception.IpException;

import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

@Slf4j
public class IpApiImpl implements IpAddress {
	@Override
	public Address getAddress(String ip) throws IpException {
		String url = "http://ip-api.com/json/" + ip + "?lang=zh-CN";
		Address address = new Address();
		address.setIp(ip);
		OkHttpClient client = new OkHttpClient().newBuilder().connectTimeout(8, TimeUnit.SECONDS)
				.readTimeout(15, TimeUnit.SECONDS).build();

		Request request = new Request.Builder().url(url)
				.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows 7)").get()
				.addHeader("Cache-Control", "no-cache").build();
		try {
			Response response = client.newCall(request).execute();
			if (response.isSuccessful()) {
				String result = response.body().string();
				log.debug("ip-api.com getAddress result:{},{}", url, result);
				JSONObject obj = JSON.parseObject(result);
				if ("success".equals(obj.getString("status"))) {
					address.setCountry(obj.getString("country"));
					address.setProvince(obj.getString("regionName"));
					address.setCity(obj.getString("city"));
					address.setOrganization(obj.getString("isp"));
				} else if ("fail".equals(obj.getString("status"))) {
					if ("private range".equals(obj.getString("message"))) {
						address.setCountry("XX");
						address.setProvince("XX");
						address.setCity("内网IP");
						address.setOrganization("内网IP");
						return address;
					} else if ("invalid query".equals(obj.getString("message"))) {
						address.setOrganization("错误的IP");
						return address;
					}
				}
			}
		} catch (IOException e1) {
			throw new IpException("取信息出错:" + e1.getMessage());
		}

		url = "http://ip.ws.126.net/ipquery?ip=" + ip;
		request = new Request.Builder().url(url)
				.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows 7)").get()
				.addHeader("Cache-Control", "no-cache").build();
		try {
			Response response = client.newCall(request).execute();
			if (response.isSuccessful()) {
				String result = response.body().string();
				int index = result.indexOf("{");
				result = result.substring(index);
				log.debug("ip-api.com getAddress result:{},{}", url, result);
				JSONObject obj = JSON.parseObject(result);
				if (!"".equals(obj.getString("city"))) {
					address.setProvince(obj.getString("province"));
					address.setCity(obj.getString("city"));
				}
			}
		} catch (IOException e1) {
			throw new IpException("取信息出错:" + e1.getMessage());
		}
		return address;
	}
}
